package com.mrzhou.web.secure.aspect;

import com.mrzhou.core.tool.utils.ClassUtil;
import com.mrzhou.core.tool.utils.StringUtil;
import com.mrzhou.web.secure.annotation.BeforeAuth;
import com.mrzhou.web.secure.auth.AuthFunc;
import com.mrzhou.web.secure.exception.SecureAuthException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.lang.reflect.Method;

@Aspect
public class AuthAspect implements ApplicationContextAware {

    private final ExpressionParser parser = new SpelExpressionParser();

    private ApplicationContext applicationContext;

    @Around("@annotation(com.mrzhou.web.secure.annotation.BeforeAuth) || @within(com.mrzhou.web.secure.annotation.BeforeAuth)")
    public Object beforeAuth(ProceedingJoinPoint point) throws Throwable {
        // 获取方法签名(通过此签名获取目标方法信息)
        MethodSignature signature = (MethodSignature) point.getSignature();
        // 获取当前动态代理的对象
        Method method = signature.getMethod();
        BeforeAuth beforeAuth = ClassUtil.getAnnotation(method, BeforeAuth.class);
        String value = beforeAuth.value();
        if(StringUtil.isBlank(value)) {
            // 如果注解没有任何数据, 则不拦截
            return point.proceed();
        }
        Expression expression = parser.parseExpression(value);
        StandardEvaluationContext context = new StandardEvaluationContext(new AuthFunc());
        context.setBeanResolver(new BeanFactoryResolver(this.applicationContext));
        Boolean flag = expression.getValue(context, Boolean.class);

        if(flag) {
            return point.proceed();
        }
        throw new SecureAuthException();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
